import json
from typing import Dict, List

import requests
from casdoor.permission import Permission
from casdoor.role import Role

from config.config import Config
from module_admin.entity.vo.user_vo import CasdoorUserForUpdatePassword


class NewUser:
    def __init__(self):
        self.address = [""]
        self.affiliation = ""
        self.avatar = ""
        self.createdTime = ""
        self.dingtalk = ""
        self.displayName = ""
        self.email = ""
        self.facebook = ""
        self.gitee = ""
        self.github = ""
        self.kakao = ""
        self.google = ""
        self.lastfm = ""
        self.gitlab = ""
        self.hash = ""
        self.id = ""
        self.isAdmin = False
        self.isForbidden = False
        self.isGlobalAdmin = False
        self.language = ""
        self.name = ""
        self.owner = ""
        self.password = ""
        self.phone = ""
        self.preHash = ""
        self.qq = ""
        self.score = 0
        self.signupApplication = ""
        self.tag = ""
        self.type = ""
        self.updatedTime = ""
        self.wechat = ""
        self.weibo = ""
        self.groups = []
        self.permissions = []
        self.roles = []

    @classmethod
    def new(cls, owner, name, created_time, display_name):
        self = cls()
        self.name = name
        self.owner = owner
        self.createdTime = created_time
        self.displayName = display_name
        return self

    @classmethod
    def from_dict(cls, data: dict):
        if data is None:
            return None

        user = cls()
        for key, value in data.items():
            if hasattr(user, key):
                setattr(user, key, value)
        return user

    def __str__(self):
        return str(self.__dict__)

    def to_dict(self) -> dict:
        return self.__dict__


class NewUserSDK:
    @classmethod
    def get_users(cls) -> List[Dict]:
        """
        Get the users from Casdoor.

        :return: a list of dicts containing user info
        """
        url = Config.sdk.endpoint + "/api/get-users"
        params = {
            "owner": Config.sdk.org_name,
            "clientId": Config.sdk.client_id,
            "clientSecret": Config.sdk.client_secret,
        }
        r = requests.get(url, params)
        response = r.json()
        if response["status"] != "ok":
            raise Exception(response["msg"])
        users = []
        for user in response["data"]:
            users.append(NewUser.from_dict(user))
        return users

    @classmethod
    def get_user(cls, user_id: str) -> Dict:
        """
        Get the user from Casdoor providing the user_id.

        :param user_id: the id of the user
        :return: a dict that contains user's info
        """
        url = Config.sdk.endpoint + "/api/get-user"
        params = {
            "id": f"{Config.sdk.org_name}/{user_id}",
            "clientId": Config.sdk.client_id,
            "clientSecret": Config.sdk.client_secret,
        }
        r = requests.get(url, params)
        response = r.json()
        if response["status"] != "ok":
            raise Exception(response["msg"])
        return NewUser.from_dict(response["data"])

    @classmethod
    def edit_user_password(cls, casdoor_user_for_update: CasdoorUserForUpdatePassword, user_name: str) -> Dict:
        url = Config.sdk.endpoint + "/api/set-password"
        params = {
            "owner": Config.sdk.org_name,
            "clientId": Config.sdk.client_id,
            "clientSecret": Config.sdk.client_secret,
        }
        datas = {
            "userOwner": {Config.sdk.org_name},
            "userName": {user_name},
            "oldPassword": {casdoor_user_for_update.password},
            "newPassword": {casdoor_user_for_update.new_password}
        }
        r = requests.post(url, params=params, data=datas)
        response = r.json()
        if response["status"] != "ok":
            raise Exception(response["msg"])
        return response

    @classmethod
    def get_user_count(cls, is_online: bool = None) -> int:
        """
        Get the count of filtered users for an organization
        :param is_online: True for online users, False for offline users,
                          None for all users
        :return: the count of filtered users for an organization
        """
        url = Config.sdk.endpoint + "/api/get-user-count"
        params = {
            "owner": Config.sdk.org_name,
            "clientId": Config.sdk.client_id,
            "clientSecret": Config.sdk.client_secret,
        }

        if is_online is None:
            params["isOnline"] = ""
        else:
            params["isOnline"] = "1" if is_online else "0"

        r = requests.get(url, params)
        count = r.json()
        return count

    @classmethod
    def modify_user(cls, method: str, user: NewUser) -> Dict:
        url = Config.sdk.endpoint + f"/api/{method}"
        user.owner = Config.sdk.org_name
        params = {
            "id": f"{user.owner}/{user.name}",
            "clientId": Config.sdk.client_id,
            "clientSecret": Config.sdk.client_secret,
        }
        user_info = json.dumps(user.to_dict())
        r = requests.post(url, params=params, data=user_info)
        response = r.json()
        if response["status"] != "ok":
            raise Exception(response["msg"])
        return response

    @classmethod
    def add_user(cls, user: NewUser) -> Dict:
        response = cls.modify_user("add-user", user)
        return response

    @classmethod
    def update_user(cls, user: NewUser) -> Dict:
        response = cls.modify_user("update-user", user)
        return response

    @classmethod
    def delete_user(cls, user: NewUser) -> Dict:
        response = cls.modify_user("delete-user", user)
        return response
